#!/usr/bin/env python
# coding: utf-8

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db

import module.user_manage
import locale

def delete_all_products():
    while True:
        q = db.GqlQuery("SELECT * FROM Products")
        results = q.fetch(500)
        if len(results) == 0:
            break
        
        for result in results:
            result.delete()
            
def create_dummy_users(startidx, endidx):
    count = 0
    for i in range(startidx, endidx):
        user_id = "test_" + locale.format('%03d', i)
        user_email = user_id + "@gmail.com"
        deposit = 10000
        
        ret = module.user_manage.UserManager.add_new_user(user_id, user_email, deposit)
        if ret==0:
            count+=1
    return count
        
        

class MainHandler(webapp.RequestHandler):
    def get(self):
 
        method = self.request.get('method')
        try:
            startidx = int(self.request.get('start'))
        except:
            startidx=1
        try:
            endidx = int(self.request.get('limit'))
            endidx = endidx + startidx
        except:
            endidx=101
                
        if method == "delete_all_products":
            delete_all_products()
            self.response.out.write("Complete all products records!!")
        elif method == "create_dummy_user":
            count = create_dummy_users(startidx, endidx)
            self.response.out.write("Complete to create dummy user from test_"+ 
                                    str(startidx) + " to test_"+str(endidx) + "  Count:" +str(count))            

def main():
    application = webapp.WSGIApplication([('/admin', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()